import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:zhuhu_demo/domain/home/news_model.dart';
import 'package:flutter_swiper_null_safety/flutter_swiper_null_safety.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:zhuhu_demo/domain/home/provider/stories_provider.dart';
import 'package:zhuhu_demo/domain/home/provider/top_stories_provider.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'subviews/home_card.dart';
import 'subviews/home_date_card.dart';
import '../../service/route_names.dart';
import './home_page_viewmodel.dart';
import './subviews/home_topbar_date.dart';

class HomePage extends ConsumerStatefulWidget {
  const HomePage({super.key});

  @override
  ConsumerState<ConsumerStatefulWidget> createState() => _HomeState();
}

class _HomeState extends ConsumerState<HomePage> {

  late final AsyncNotifierProvider<TopStoriesNotifier, List<NewsModel>>
      topStoriesProvider;
  late final AsyncNotifierProvider<StoriesNotifier, List<NewsListModel>>
      storiesProvider;
  late final ScrollController _controller;

  @override
  void initState() {
    super.initState();

    initProvider();
    initScrollController();
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }

  void initProvider() {
    HomePageViewModel viewModel = HomePageViewModel();
    topStoriesProvider =
        AsyncNotifierProvider<TopStoriesNotifier, List<NewsModel>>(
            () => TopStoriesNotifier(viewModel: viewModel));
    storiesProvider =
        AsyncNotifierProvider<StoriesNotifier, List<NewsListModel>>(
            () => StoriesNotifier(viewModel: viewModel));

  }

  void initScrollController() {
    _controller = ScrollController();
    _controller.addListener(() {
      if (_controller.position.maxScrollExtent == 0) {
        return;
      }
      if (_controller.position.pixels == _controller.position.maxScrollExtent) {
        var notifier = ref.read(storiesProvider.notifier);
        notifier.loadMore();
      }
    });
  }

  Widget headerPage(BuildContext context) {
    return SizedBox(
        height: 400.0.h,
        child: Consumer(builder: (context, ref, child) {
          var asyncValue = ref.watch(topStoriesProvider);
          return asyncValue.when(
              data: (topStories) {
                return Swiper(
                    itemBuilder: (context, index) {
                      return CachedNetworkImage(
                          imageUrl: topStories[index].imageUrl,
                          fit: BoxFit.cover);
                    },
                    itemCount: topStories.length,
                    autoplay: true,
                    onTap: (index) => onTap(context, topStories[index].url),
                    pagination: SwiperPagination(
                        alignment: Alignment.bottomRight,
                        margin: EdgeInsets.all(20.0.w),
                        builder: const DotSwiperPaginationBuilder(
                            activeColor: Colors.white, color: Colors.white60)));
              },
              error: (error, _) => Text(error.toString()),
              loading: () => const SizedBox());
        }));
  }

  Widget contentPage(BuildContext context, List<NewsListModel> stories) {
    return ListView.builder(
        controller: _controller,
        itemBuilder: (context, index) {
          switch (index) {
            case 0:
              return Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    headerPage(context),
                    ...getCards(news: stories[index].news, context: context)
                  ]);
            default:
              return Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    HomeDateCard(title: stories[index].dateString),
                    ...getCards(news: stories[index].news, context: context)
                  ]);
          }
        },
        itemCount: stories.length);
  }

  List<Widget> getCards({required List<NewsModel> news, required BuildContext context}) {
    return news.map((model) {
      return HomeCard(
          title: model.title,
          subTitle: model.hint,
          rightImageUrl: model.imageUrl,
          onTap: () => onTap(context, model.url));
    }).toList();
  }

  void onTap(BuildContext context, String url) {
    Navigator.pushNamed(context, RouteNames.shared.web,
        arguments: {'url': url});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
            leading: const HomeTopbarDate(),
            leadingWidth: 70.0.w,
            title: Text('知乎日报', style: TextStyle(fontSize: 24.sp, fontWeight: FontWeight.w800)),
            backgroundColor: Colors.white,
            foregroundColor: Colors.black,
            centerTitle: false,
            titleSpacing: 5.w),
        body: Consumer(builder: (builder, ref, child) {
          var asyncValue = ref.watch(storiesProvider);
          return asyncValue.when(
            data: (stories) => contentPage(context, stories), 
            error: (error, _) => Text(error.toString()), 
            loading: () => const Center(child: CircularProgressIndicator()));
        }));
  }
}